package com.sharewithus.service;

import java.io.IOException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
import sharewithus.business.dto.UserIntegralDTO;

import com.sharewithus.dao.impl.UserDAOImpl;
import com.sharewithus.utlis.FormatUtil;
import com.thoughtworks.xstream.XStream;
import common.Common;

/**
 * @author bubei
 * 储存日志类
 *
 */
public class UserService {
	
	private static ClassPathXmlApplicationContext appContext = null;
	public static BeanFactory factory = null;
	private static ShardedJedisPool jedisPool = null;
	
	public UserService() throws IOException{
		appContext = new ClassPathXmlApplicationContext(Common.SHAREWITHUS_SPRING_CONFIG);
		factory = (BeanFactory) appContext;
		jedisPool = (ShardedJedisPool)factory.getBean("jedisPool");
	}
	
	
	/**
	 * @param l
	 * @return
	 */
	public void saveUserIntegral(UserIntegralDTO ui){
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("description", ui.getDescription());
		param.put("expennd", ui.getExpennd());
		param.put("flag", ui.getFlag());
		param.put("income", ui.getIncome());
		param.put("remarks", ui.getRemarks());
		try {
	        param.put("takeTime", FormatUtil.StringToDate(ui.getTakeTime()));
        } catch (ParseException e) {
	        // TODO Auto-generated catch block
	        e.printStackTrace();
        }
		param.put("type", ui.getType());
		param.put("userId", ui.getUserId());
		UserDAOImpl userDAO = (UserDAOImpl)factory.getBean("userDAO");
		userDAO.saveUserIntegral(param);
		
		
		ShardedJedis jedis = jedisPool.getResource();
		try{
			
			int sum = 0;
			if(!(jedis.get(ui.getUserId() + "IntegralSum") == null || jedis.get(ui.getUserId() + "IntegralSum").equalsIgnoreCase("") || jedis.get(ui.getUserId() + "IntegralSum").equalsIgnoreCase("null"))){
				sum = Integer.parseInt(jedis.get(ui.getUserId() + "IntegralSum"));
			}
			if(ui.getType() == 1){
				jedis.del(ui.getUserId() + "IntegralSum");
				jedis.set(ui.getUserId() + "IntegralSum",String.valueOf(sum+ui.getIncome()));
			}else if(ui.getType() == 0){
				jedis.del(ui.getUserId() + "IntegralSum");
				jedis.set(ui.getUserId() + "IntegralSum",String.valueOf(sum+ui.getExpennd()));
			}
			XStream stream=new XStream();
			stream.alias("UserIntegralDTO", UserIntegralDTO.class);
			String xml=stream.toXML(ui);
	        jedis.lpush(ui.getUserId() + "Integrals",xml);
		} catch (Exception e) {  
            //logger.error(e);  
            e.printStackTrace();  
        } finally {  
            jedisPool.returnResource(jedis);  
        } 
	}
	
}
